#!/usr/bin/env python3
"""
MAESS智能体系统 - 真实环境服务检查脚本
基于Docker实际运行配置
"""

import sys
import os
from loguru import logger

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

try:
    import redis
except ImportError:
    logger.error("redis 模块未安装，正在安装...")
    os.system("pip install redis")
    import redis

try:
    import pymysql
except ImportError:
    logger.error("pymysql 模块未安装，正在安装...")
    os.system("pip install pymysql")
    import pymysql

try:
    import pika
except ImportError:
    logger.error("pika 模块未安装，正在安装...")
    os.system("pip install pika")
    import pika

# 基于Docker实际运行配置
# 根据你的docker ps输出，服务都在192.168.64.100上
REDIS_HOST = '192.168.64.100'
REDIS_PORT = 6379
REDIS_PASSWORD = ''

MYSQL_HOST = '192.168.64.100'
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'root'  # 默认root密码
MYSQL_DATABASE = 'maess'

RABBITMQ_HOST = '192.168.64.100'
RABBITMQ_PORT = 5672
RABBITMQ_USER = 'guest'
RABBITMQ_PASSWORD = 'guest'


def check_redis():
    """检查Redis连接"""
    try:
        redis_client = redis.Redis(
            host=REDIS_HOST, 
            port=REDIS_PORT, 
            password=REDIS_PASSWORD or None,
            socket_connect_timeout=5,
            socket_timeout=5,
            decode_responses=True
        )
        redis_client.ping()
        info = redis_client.info()
        
        logger.success(f"✅ Redis连接正常 (版本: {info.get('redis_version', 'unknown')})")
        logger.info(f"   内存使用: {info.get('used_memory_human', 'unknown')}")
        logger.info(f"   连接客户端: {info.get('connected_clients', 0)}")
        return True
    except Exception as e:
        logger.error(f"❌ Redis连接失败: {e}")
        return False


def check_mysql():
    """检查MySQL连接"""
    try:
        conn = pymysql.connect(
            host=MYSQL_HOST,
            port=MYSQL_PORT,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            database=MYSQL_DATABASE,
            connect_timeout=5,
            charset='utf8mb4'
        )
        
        with conn.cursor() as cursor:
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()[0]
            
            # 检查数据库是否存在
            cursor.execute("SHOW DATABASES LIKE %s", (MYSQL_DATABASE,))
            db_exists = cursor.fetchone() is not None
        
        conn.close()
        
        logger.success(f"✅ MySQL连接正常 (版本: {version})")
        logger.info(f"   数据库 '{MYSQL_DATABASE}' 存在: {'是' if db_exists else '否'}")
        return True
    except Exception as e:
        logger.error(f"❌ MySQL连接失败: {e}")
        logger.info(f"   连接参数: {MYSQL_HOST}:{MYSQL_PORT}, 用户: {MYSQL_USER}")
        return False


def check_rabbitmq():
    """检查RabbitMQ连接"""
    try:
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=RABBITMQ_HOST,
                port=RABBITMQ_PORT,
                credentials=pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD),
                connection_attempts=1,
                socket_timeout=5,
                heartbeat=0  # 禁用心跳避免连接问题
            )
        )
        
        channel = connection.channel()
        # 测试声明一个临时队列
        channel.queue_declare(queue='test_queue', auto_delete=True)
        
        connection.close()
        
        logger.success("✅ RabbitMQ连接正常")
        logger.info(f"   管理界面: http://{RABBITMQ_HOST}:15672")
        return True
    except Exception as e:
        logger.error(f"❌ RabbitMQ连接失败: {e}")
        logger.info(f"   连接参数: {RABBITMQ_HOST}:{RABBITMQ_PORT}, 用户: {RABBITMQ_USER}")
        return False


def main():
    """主函数"""
    logger.info("开始检查MAESS系统服务状态...")
    logger.info("="*60)
    logger.info("检查的服务配置 (基于Docker实际运行):")
    logger.info(f"  Redis: {REDIS_HOST}:{REDIS_PORT}")
    logger.info(f"  MySQL: {MYSQL_HOST}:{MYSQL_PORT} (用户: {MYSQL_USER})")
    logger.info(f"  RabbitMQ: {RABBITMQ_HOST}:{RABBITMQ_PORT} (用户: {RABBITMQ_USER})")
    logger.info("="*60)
    
    results = {
        'Redis': check_redis(),
        'MySQL': check_mysql(),
        'RabbitMQ': check_rabbitmq()
    }
    
    logger.info("\n" + "="*60)
    logger.info("服务状态检查结果:")
    for service, status in results.items():
        status_icon = "✅" if status else "❌"
        logger.info(f"{status_icon} {service}: {'正常' if status else '异常'}")
    
    total_services = len(results)
    healthy_services = sum(results.values())
    
    if healthy_services == total_services:
        logger.success(f"\n🎉 所有服务运行正常！({healthy_services}/{total_services})")
        logger.info("现在可以启动MAESS系统了！")
        return 0
    else:
        logger.warning(f"\n⚠️  部分服务异常 ({healthy_services}/{total_services})")
        logger.info("请检查服务配置或Docker容器状态")
        return 1


if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        logger.info("服务检查被中断")
        sys.exit(1)
    except Exception as e:
        logger.error(f"服务检查失败: {e}")
        sys.exit(1)